# -*- coding: utf-8 -*-
# DOM dom会把整个xml读入内存 解析为书，可以任意遍历树的节点，但是占用内存解析慢
# SAX 流模式 边读边解析  优先考虑SAX

# SAX start_element end_element char_data

from xml.parsers.expat import ParserCreate

class DefaultSaxHandler(object):
	def start_element(self,name,attrs):
		print('sax:start_element: %s, attrs: %s'%(name,str(attrs)))

	def end_element(self,name):
		print('sax:end_element:%s'% name)

	def char_data(self,text):
		print('sax:char_data:%s'% text)
xml = r'''<?xml version="1.0"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>
'''
handler = DefaultSaxHandler()
parser = ParserCreate()
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)

# 生成xml 拼接字符串
	L = []
	L.append(r'<?xml version="1.0"?>')
	L.append(r'<root>')
	L.append(encode('some & data'))
	L.append(r'</root>')
	return ''.join(L)